﻿using FluorineFx.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace lxwmvc
{   
    /// <summary>
    /// 微信回调地址，微信服务器处理事件
    /// </summary>
    public class weixincontroller
    {
#if DEBUG
        //测试
        //static string APPID = "wxd302067a9ce50e33";
        //static string APPSECRET = "879081d8d9198190f2deb4cfc0ba50cd";
        //static string KEY = "lixiaowei";
        //public static string domain = "www.etuling.com";

        static string APPID = "wxb33317e910a8519d";
        static string APPSECRET = "7979cd0bf3e7c98d302d52b183ea64ed";
        static string KEY = "dianjin";
        public static string domain = "ad.zituibao.com";
#else
        //自推宝 配置信息
        public static string domain = "z.zituibao.com";
        static string APPID = "wx8f74c13f708a5f4e";
        static string APPSECRET = "cdc1cd7374a6a815976d84824f518926";
        static string KEY = "lixiaowei";

        //public static string domain = "z.yunto.cc";
        //static string APPID = "wxb33317e910a8519d";
        //static string APPSECRET = "7979cd0bf3e7c98d302d52b183ea64ed";
        //static string KEY = "lixiaowei";
#endif
        //微信授权完毕回调
        public const string URL = "http://ad.zituibao.com/weixin/index_jm";
        public const string SCOPE = "snsapi_base";

        //云图点金
        //public static string APPID = "wx42fb911566d56463";
        public static WeiXin_GongZhongHao GZH = new WeiXin_GongZhongHao(
            APPID
            , APPSECRET
            , KEY,domain
            );

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="pb"></param>
        public static void message(pagebase pb)
        {
            pb.cancelview();
            if (GZH.ValidServerUrl()) return;

            //接收xml信息
            string content = GetRequestInputStream(pb);
            GZH.Event(typeof(defaultcontroller), content);
        }


        /// <summary>
        /// 得到微信传递过来的信息
        /// </summary>
        /// <param name="pb"></param>
        /// <returns></returns>
        static string GetRequestInputStream(pagebase pb)
        {
            string content = "";
            using (StreamReader sb = new StreamReader(pb.Request.InputStream, Encoding.UTF8))
            {
                content = sb.ReadToEnd();
            }
            return content;
        }

        public static void index(pagebase pb)
        {
            var context = getparams(pb);

            //通过授权得到code
            var code = pb.get<string>("code");
            var state = pb.get<string>("state");

            if (code.isnull() && state.isnotnull())
            {                
                //pb.write("本网站需要用户授权才能操作，请点击按钮重新授权");
                pb["login_url"] = pb.Session["login_url"];
                pb["message"] = "我们需要微信授权才能操作，请重新授权";
                return;
            }

            //code无法得到
            if (code.isnull())
            {
                pb["login_url"] = pb.Session["login_url"];
                pb["message"] = "授权出现异常，请重新授权";
                return;
            }

            //这里面应该会包含openid unionid access_token,如果成功的话
            var token = weixincontroller.GZH.GetWebAccess_Token(code);

            var yonghu = new _yonghu();

            //拉取用户信息，但是如果用户未关注，是拉取不到用户信息的
            var info = weixincontroller.GZH.GetInfo(token.openid);
            if (info.subscribe == 0)//代表为关注
            {
                var userinfo = weixincontroller.GZH.GetUserInfo(token.access_token, token.openid);
                //存储到数据库？ 未关注
                yonghu.city = userinfo.city;
                yonghu.country = userinfo.country;
                yonghu.headimgurl = userinfo.headimgurl;
                yonghu.nickname = userinfo.nickname;
                yonghu.openid = userinfo.openid;
                yonghu.province = userinfo.province;
                yonghu.sex = userinfo.sex;
                yonghu.unionid = userinfo.unionid;
            }
            else
            {
                yonghu.city = info.city;
                yonghu.country = info.country;
                yonghu.headimgurl = info.headimgurl;
                yonghu.nickname = info.nickname;
                yonghu.openid = info.openid;
                yonghu.province = info.province;
                yonghu.sex = info.sex;
                yonghu.unionid = info.unionid;
                yonghu.subscribe = info.subscribe;
                yonghu.subscribe_time = info.subscribe_time;
            }

            //存储用户信息
            yonghu.saveorupdate();

            //他们的信息都存储到user表里面 综合一下信息
                
            //记录cookes信息，然后重定向到原来的页面
            cookieshelper.setcookie("unionid", info.unionid);
            cookieshelper.setcookie("openid", info.openid);

            if (pb.Session["login_url"].tostr() == "")
                throw new Exception("session 过期");

            //这里可能会出现问题，就是直接跳转
            pb.cancelview();
            pb.redirect(pb.Session["login_url"].tostr());

            //pb.write(context);
        }

        /// <summary>
        /// 静默授权
        /// </summary>
        /// <param name="pb"></param>
        public static void index_jm(pagebase pb)
        {
            var context = getparams(pb);

            //通过授权得到code
            var code = pb.get<string>("code");
            //var state = pb.get<string>("state");

            //if (code.isnull() && state.isnotnull())
            //{
            //    //pb.write("本网站需要用户授权才能操作，请点击按钮重新授权");
            //    pb["login_url"] = pb.Session["login_url"];
            //    pb["message"] = "我们需要微信授权才能操作，请重新授权";
            //    return;
            //}

            //code无法得到
            if (code.isnull())
            {
                pb["login_url"] = pb.Session["login_url"];
                pb["message"] = "授权出现异常，请重新授权";
                return;
            }

            //这里面应该会包含openid unionid access_token,如果成功的话
            dataloger.info(code);
            var token = weixincontroller.GZH.GetWebAccess_Token(code);

            var yonghu = queryhelper.get<_yonghu>("select * from yonghu where openid=@0", token.openid);
            if( yonghu == null) yonghu = new _yonghu();
            yonghu.openid = token.openid;
            yonghu.tianjiariqi = DateTime.Now;
            //默认为VIP用户
            yonghu.style = 1;
            
            //存储用户信息
            yonghu.saveorupdate();

            //他们的信息都存储到user表里面 综合一下信息

            //记录cookes信息，然后重定向到原来的页面
            cookieshelper.setcookie("openidx", yonghu.openid);

            if (pb.Session["login_url"].tostr() == "")
                throw new Exception("session 过期");

            //这里可能会出现问题，就是直接跳转
            pb.cancelview();
            pb.redirect(pb.Session["login_url"].tostr());

            //pb.write(context);
        }

        public static void index_pc(pagebase pb)
        {

            cookieshelper.setcookie("openidx", DateTime.Now.ToString("yyyyMMddHHmmssfff") + WeiXin_Fun.CreateNonceStr(10));
            //cookieshelper.setcookie("openidx", yonghu.openid);

            if (pb.Session["login_url"].tostr() == "")
                throw new Exception("session 过期");

            //这里可能会出现问题，就是直接跳转
            pb.cancelview();
            pb.redirect(pb.Session["login_url"].tostr());

            //pb.write(context);
        }


        static string getparams(pagebase pb)
        {
            StringBuilder sb = new StringBuilder();
            if (pb.Request.Form.Keys.Count > 0)
            {
                sb.AppendLine("Form:");
                foreach (string o in pb.Request.Form.Keys)
                    sb.AppendLine(o + "=" + (pb.Request.Form[o] == null ? "NULL" : pb.Request.Form[o].tostr()));
            }

            //查询添加
            if (pb.Request.QueryString.Keys.Count > 0)
            {
                sb.AppendLine("QueryString:");
                foreach (string o in pb.Request.QueryString.Keys)
                    sb.AppendLine(o + "=" + (pb.Request.QueryString[o] == null ? "NULL" : pb.Request.QueryString[o].tostr()));
            }

            return sb.tostr().Replace("\n", "<br/>");
        }

        /// <summary>
        /// 分享出去的页面，可以带参数  fenxiang这个页面可以任意设定
        /// </summary>
        /// <param name="pb"></param>
        public static void fenxiang(pagebase pb)
        {
            //处理分享关系
            weixincontroller.GZH.JSSDK_FX();

            //分享页面验签
            var arr = weixincontroller.GZH.JSSDK();

            //分享的地址必须是fenxaing一致，只是参数不一致
            arr["link"] = "分享的地址";
            arr["title"] = "标题";
            arr["miaoshu"] = "描述";
            arr["pic"] = "图片";

            pb["weixin"] = arr;
        }

        public static void model(pagebase pb)
        {
            pb.cancelview();
            applicationhelper.CreateModels("");
        }
    }
}
